﻿var RECOGNITION_SERVICE_URL = "http://localhost:1374/Service/service.svc/GetRecognitionData";
var RATE = 22;
var GAIN = 100;
var SILENCE_LEVEL = 10;
var SILENCE_TIMEOUT = 2000;

window.onload = function () {
    $('#automaticMode').attr('checked', false);
};

function randomString(length) {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var randomstring = '';
    for (var i=0; i<length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum,rnum+1);
    }
    return randomstring;
}

function callRecognitionService(base64Str) {
	bytes = "data:audio/wav;base64,"+base64Str;
	var audio = new Audio();
	audio.setAttribute("src", bytes);
	audio.load();
	audio.play();

	BUFFER_LENGTH = 65000;
	var data = new Array();
	var n = Math.floor(base64Str.length / BUFFER_LENGTH);
	
	for (var i = 0; i < n ; ++i)
	    data[i] = base64Str.substring(i * BUFFER_LENGTH, (i + 1) * BUFFER_LENGTH);
	if (n * BUFFER_LENGTH < base64Str.length) {
	    data[n] = base64Str.substring(n * BUFFER_LENGTH, base64Str.length);
	    n += 1;
	}

	var ID = randomString(20);
	for (var i = 0; i < n ; ++i) {
	    $.ajax({
	        url: RECOGNITION_SERVICE_URL,
	        dataType: "jsonp",
	        type: "POST",
	        contentType: "application/json; charset=utf-8",
	        data: JSON.stringify({ ID:ID, length:n, blockIndex:i, base64: data[i] }),
	        success: function (data) {
	            if (data.finalResult)
	                alert(data.text);
	        }
	    });
	}
}

function microphone_recorder_events()
{

  switch(arguments[0]) {
  case "ready":
    var width = parseInt(arguments[1]);
    var height = parseInt(arguments[2]);
    Recorder.connect("recorderApp", 0);
    Recorder.recorderOriginalWidth = width;
    Recorder.recorderOriginalHeight = height;
  break;

  case "no_microphone_found":
    break;

  case "microphone_user_request":
    Recorder.showPermissionWindow();
    break;

  case "microphone_connected":
    var mic = arguments[1];
    Recorder.defaultSize();
    $('#microphone').text(mic.name);
    Recorder.configure();
    break;

  case "microphone_not_connected":
    Recorder.defaultSize();
    break;

  case "microphone_activity":
    var txt;
    if (arguments[1])
        txt = "Đang nhận lệnh";
    else
        txt = "Chờ ra lệnh";
    $('#status').text(txt);
    break;

  case "microphone_level":
    $('#activityLevel').text(arguments[1]);
    break;

  case "recording":
    $('#buttonRecord').attr('value', 'Dừng ra lệnh');
    break;

  case "recording_stopped":
    var duration = arguments[1];
    $('#buttonRecord').attr('value', 'Ra lệnh');
    break;

  }
}

Recorder = {
  recorder: null,
  recorderOriginalWidth: 0,
  recorderOriginalHeight: 0,

  connect: function(name, attempts) {
    if(navigator.appName.indexOf("Microsoft") != -1) {
      Recorder.recorder = window[name];
    } else {
      Recorder.recorder = document[name];
    }

    if(attempts >= 40) {
      return;
    }

    setTimeout(function() {Recorder.connect(name, attempts+1);}, 100);
  },

  configure: function () {
      Recorder.recorder.configure(RATE, GAIN, SILENCE_LEVEL, SILENCE_TIMEOUT);
  },

  setAutoRecord: function (checked) {
      Recorder.recorder.setAutoRecord(checked);
  },

  record: function() {
    Recorder.recorder.record();
  },

  resize: function(width, height) {
    Recorder.recorder.width = width + "px";
    Recorder.recorder.height = height + "px";
  },

  defaultSize: function(width, height) {
    Recorder.resize(Recorder.recorderOriginalWidth, Recorder.recorderOriginalHeight);
  },

  showPermissionWindow: function() {
    Recorder.resize(240, 160);
    // need to wait until app is resized before displaying permissions screen
    setTimeout(function(){Recorder.recorder.permit();}, 1);
  }
}